package nowcode;

import java.util.ArrayList;
import java.util.LinkedList;

public class MaxInWindowSolution {

    public static void main(String[] args) {
        MaxInWindowSolution solution = new MaxInWindowSolution();

        ArrayList<Integer> integers = solution.maxInWindows(new int[]{2, 3, 4, 2, 6, 2, 5, 1}, 3);
        integers.forEach(System.out::println);
    }

    public ArrayList<Integer> maxInWindows(int[] num, int size) {

        ArrayList<Integer> list = new ArrayList<>();

        if (num.length == 0 || size == 0 || size > num.length) {
            return list;
        }

        LinkedList<Integer> indexStack = new LinkedList<>();
        for (int i = 0; i < size; i++) {
            while (!indexStack.isEmpty() && num[indexStack.peekLast()] < num[i]) {
                indexStack.pollLast();
            }
            indexStack.add(i);
        }
        list.add(num[indexStack.peekFirst()]);

        for (int i = 1; i < num.length - size + 1; i++) {
            while (!indexStack.isEmpty() && indexStack.peekFirst() < i) {
                indexStack.pollFirst();
            }
            while (!indexStack.isEmpty() && num[indexStack.peekLast()] < num[i + size - 1]) {
                indexStack.pollLast();
            }
            indexStack.add(i + size - 1);
            list.add(num[indexStack.peekFirst()]);
        }
        return list;
    }


    public ArrayList<Integer> maxInWindows2(int[] num, int size) {

        ArrayList<Integer> result = new ArrayList<>();

        if (num.length == 0 || size == 0) {
            return result;
        }
        int[] maxHeap = new int[size];
        for (int j = 0; j < num.length - size + 1; j++) {
            for (int i = 0; i < size; i++) {
                maxHeap[i] = num[j + i];
            }
            buildMaxHeap(maxHeap);
            result.add(maxHeap[0]);
        }
        return result;
    }

    private void buildMaxHeap(int[] nums) {
        int nodeIndex = (nums.length - 1) / 2;
        for (; nodeIndex >= 0; nodeIndex--) {
            adjustMaxHeap(nums, nums.length, nodeIndex);
        }
    }


    private void adjustMaxHeap(int[] nums, int length, int nodeIndex) {
        if (length <= 1) {
            return;
        }
        int leftIndex = (nodeIndex + 1) * 2 - 1;
        int rightIndex = (nodeIndex + 1) * 2;
        if (leftIndex < length) {
            if (nums[nodeIndex] < nums[leftIndex]) {
                int temp = nums[nodeIndex];
                nums[nodeIndex] = nums[leftIndex];
                nums[leftIndex] = temp;
                adjustMaxHeap(nums, length, leftIndex);
            }
        }
        if (rightIndex < length) {
            if (nums[nodeIndex] < nums[rightIndex]) {
                int temp = nums[nodeIndex];
                nums[nodeIndex] = nums[rightIndex];
                nums[rightIndex] = temp;
                adjustMaxHeap(nums, length, rightIndex);
            }
        }
    }
}
